#include "single_link.h"
#include <stdio.h>
#include <stdlib.h>


void errormsg(int result,const char* msg)
{
    if (ERROR == result) {
        printf("Error:%s\n",msg);
    } else if (INFO == result){
        printf("Info:%s\n",msg);
    } else {
        printf("error result %d, text %s\n", result ,msg);
    }
    return ;
}

SingleLinkNode* init_link(SingleLinkNode* data)
{
    data = (SingleLinkNode*)malloc(sizeof(SingleLinkNode));
    if(NULL == data)
    {
        errormsg(ERROR,"init_link error");
        return NULL;
    }
    data->next = NULL;
    return data;
}

void destory_link(SingleLinkNode* data)
{
    SingleLinkNode* temp = NULL;
    while(data != NULL)
    {
        temp = data;
        data = data->next;
        free(temp);
    }
}

void push_front(SingleLinkNode* data,int value)
{
    SingleLinkNode* new_node = NULL;
    SingleLinkNode* temp = NULL;
    
    new_node = (SingleLinkNode*)malloc(sizeof(SingleLinkNode));
    if (NULL == new_node) {
        errormsg(ERROR,"malloc memory error");
        return ;
    }
    new_node->data = value;
    temp = data->next;
    data->next = new_node;
    new_node->next = temp;
}

void push_back(SingleLinkNode* data,int value)
{
    SingleLinkNode* new_node = NULL;
    SingleLinkNode* temp = data;
    
    temp = data;
    printf("------------push back find:--------------\n");
    while(temp != NULL){
        printf("%d->",temp->data);
        temp = temp->next;
    }
    printf("NULL\n");
    printf("------------push back find end------------\n");

    new_node = (SingleLinkNode *)malloc(sizeof(SingleLinkNode));
    if (NULL == new_node) {
        errormsg(ERROR,"malloc memory error");
        return ;
    }
    new_node->data = value;
    new_node->next = NULL;

    temp = data;
}


SingleLinkNode* find(SingleLinkNode* data,int value)
{
    SingleLinkNode* temp = NULL;
    temp = data->next;
    while(temp != NULL)
    {
        if (temp->data == value) {
            return temp;
        }
        temp = temp->next;
    }
    return NULL;
}

void delete_value_all(SingleLinkNode* data,int value)
{
    SingleLinkNode* temp = NULL;
    SingleLinkNode* pre = data;
    temp = data->next;
    while(temp != NULL)
    {
        if (temp->data == value) {
            pre->next = temp->next;
            free(temp);
            temp = pre->next;
        } else {
            pre = temp;
            temp = temp->next;
        }
    }
}

void show(SingleLinkNode* data)
{
    SingleLinkNode* temp = NULL;

    temp = data->next;
    while(temp != NULL)
    {
        printf("%d->",temp->data);
        temp = temp->next;
    }
    printf("NULL\n");
}